package com.yida.auth.service;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.yida.common.core.constant.CacheConstants;
import com.yida.common.core.constant.Constants;
import com.yida.common.core.constant.SecurityConstants;
import com.yida.common.core.constant.UserConstants;
import com.yida.common.core.domain.R;
import com.yida.common.core.enums.UserStatus;
import com.yida.common.core.exception.ServiceException;
import com.yida.common.core.utils.StringUtils;
import com.yida.common.redis.service.RedisService;
import com.yida.common.security.properties.CoexistProperties;
import com.yida.system.api.RemoteUserService;
import com.yida.system.api.domain.SysUser;
import com.yida.system.api.domain.SysUserUkey;
import com.yida.system.api.model.LoginUser;

/**
 * @author yida
 * @date 2023/03/28
 */
@Component
public class SysUKeyLoginService {

    private static final Logger log = LoggerFactory.getLogger(SysLoginService.class);

    private final String ukeyEnabled = "sys.ukey.enabled";

    /** ukey开关 */
    // private final static String uKeyEnabled = "true";

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private SysUKeyService sysUKeyService;

    @Autowired
    private SysRecordLogService recordLogService;

    @Autowired
    private CoexistProperties coexistProperties;

    @Autowired
    private RedisService redisService;

    /**
     * 登录
     */
    public LoginUser login(String username, String password, String uKeyId, String rnd, String signUKeyStr) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
            throw new ServiceException("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
            throw new ServiceException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
            throw new ServiceException("用户名不在指定范围");
        }

        if (StringUtils.isAnyBlank(uKeyId, signUKeyStr)) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "未获取到对应UKey信息");
            throw new ServiceException("未获取到对应UKey信息");
        }

        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
            throw new ServiceException("登录用户：" + username + " 不存在[" + userResult.getMsg() + "]");
        }

        if (R.FAIL == userResult.getCode()) {
            throw new ServiceException(userResult.getMsg());
        }

        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }
        // 配置Ukey参数
        // SysUserUkey sysUKeyUser = new SysUserUkey();
        SysUserUkey sysUKeyUser = new SysUserUkey();
        sysUKeyUser.setUserName(username);
        sysUKeyUser.setPassword(user.getPassword());
        // sysUKeyUser.setPin(uKeyPin);
        sysUKeyUser.setRnd(rnd);
        sysUKeyUser.setUkeyId(uKeyId);
        sysUKeyUser.setSignUKeyStr(signUKeyStr);
        sysUKeyService.validate(sysUKeyUser, password);

        // ------------------------------------单浏览器登陆------------------------------------------
        if (!coexistProperties.getEnabled()) {
            // 如果用户不允许多终端同时登录，清除缓存信息
            String userIdKey = CacheConstants.LOGIN_USERID_KEY + user.getUserId();
            String userKey = redisService.getCacheObject(userIdKey);
            if (StringUtils.isNotEmpty(userKey)) {
                redisService.deleteObject(userIdKey);
                redisService.deleteObject(userKey);
            }
        }
        // ------------------------------------------------------------------------------

        recordLogService.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");
        return userInfo;
    }

    /**
     * 获取待验签数据
     * 
     * @param username 用户名
     * @return
     */
    public Map<String, String> waitSignMsg(String userName, String uKeyId) {
        Map<String, String> map = new HashMap<String, String>();
        SysUserUkey sysUserUkey = new SysUserUkey();
        sysUserUkey.setUserName(userName);
        sysUserUkey.setUkeyId(uKeyId);
        SysUserUkey rSysUserUkey = sysUKeyService.waitSignMsg(sysUserUkey);
        if (StringUtils.isNotNull(rSysUserUkey)) {
            map.put("pin", rSysUserUkey.getPin());
            map.put("rnd", rSysUserUkey.getRnd());
        }
        log.info("返回待签参数：[" + map + "]");
        return map;
    }

    /**
     * 检测ukey是否启用
     * 
     * @return
     */
    public boolean checkUkey() {
        boolean enabled = true;
        String redisEnabled = redisService.getCacheObject(getCacheKey(ukeyEnabled));
        if (StringUtils.isNull(redisEnabled)) {
            return enabled;
        }
        return enabled = "true".equals(redisEnabled) ? true : false;
    }

    /**
     * 获取cache key
     * 
     * @param configKey 参数键
     * @return 缓存键key
     */
    public String getCacheKey(String configKey) {
        return CacheConstants.SYS_CONFIG_KEY + configKey;
    }

}
